<template>
  <el-form
    class="login-form"
    ref="loginForm"
    :model="loginForm"
    :rules="loginFormRules">
    <el-form-item prop="username">
      <el-input
        v-model="loginForm.username"
        prefix-icon="iconfont icon-user"/>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        type="password"
        prefix-icon="iconfont icon-3702mima"/>
    </el-form-item>
    <el-form-item class="form-btns">
        <el-button
          type="primary"
          @click="login">
          登录
        </el-button>
        <el-button
          type="info"
          @click="resetLoginForm">
          重置
        </el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: 'LoginForm',
  data () {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginFormRules: {
        username: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { max: 10, min: 3, message: '长度应该在3到10', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在6到15之间', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 1. 重置表单
    resetLoginForm () {
      // for (const value in this.loginForm) {
      //   this.loginForm[value] = ''
      // }
      this.$refs.loginForm.resetFields()
    },
    // 2. 获取登录信息
    login () {
      this.$refs.loginForm.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('/login', this.loginForm)
        if (res.meta.status !== 200) return this.$message.error('登录失败!')
        this.$message.success('登录成功!')
        window.sessionStorage.setItem('token', res.data.token)
        this.$router.push('/home')
      })
    }
  }
}
</script>

<style scoped lang="less">
  .login-form {
    width: 100%;
    position: absolute;
    bottom: 0;
    padding: 0 20px;
    .form-btns {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
